package com.heima.behavior.service.impl;
import java.util.Date;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavior.mapper.ApFollowBehaviorMapper;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApFollowBehaviorService;
import com.heima.model.behavior.dtos.FollowBehaviorDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApFollowBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @作者 itcast
 * @创建日期 2021/2/4 9:57
 **/
@Service
@Slf4j
@Transactional
public class ApFollowBehaviorServiceImpl extends ServiceImpl<ApFollowBehaviorMapper,ApFollowBehavior> implements ApFollowBehaviorService {
    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;
    @Override
    public ResponseResult saveFollowBehavior(FollowBehaviorDto dto) {
        log.info("saveFollowBehavior 调用 参数为==> {}",dto);
        // 1. 查询行为实体数据
        ApBehaviorEntry behaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(dto.getUserId(), null);
        if (behaviorEntry==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"行为实体数据不存在");
        }
        // 2. 根据行为实体保存关注数据
        ApFollowBehavior followBehavior = getOne(Wrappers.<ApFollowBehavior>lambdaQuery()
                .eq(ApFollowBehavior::getArticleId, dto.getArticleId())
                .eq(ApFollowBehavior::getEntryId, behaviorEntry.getId())
                .eq(ApFollowBehavior::getFollowId, dto.getFollowId())
        );
        // 2.1 如果不存在保存关注行为
        if(followBehavior == null){
            followBehavior = new ApFollowBehavior();
            followBehavior.setEntryId(behaviorEntry.getId());
            followBehavior.setArticleId(dto.getArticleId());
            followBehavior.setFollowId(dto.getFollowId());
            followBehavior.setCreatedTime(new Date());
            save(followBehavior);
        }// 2.2 如果存在不处理
        return ResponseResult.okResult();
    }
}
